package com.chao.socket.tcp.a;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream os = null;

        try {
            // 创建服务端的serverSocket
            serverSocket = new ServerSocket(8090);
            // 使用accept接受客户端的socket 会一直阻塞 等待客户端的输入
            socket = serverSocket.accept();
            // 获取socket输入流
            is = socket.getInputStream();
            // 获取输入流中的数据
            os = new ByteArrayOutputStream();
            int len = 0;
            // 缓冲区
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer,0,len);
            }
            System.out.println("接收到客户端"+socket.getInetAddress().getHostName() + "发送的数据：" + os);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
